import * as echarts from '../../../ec-canvas/echarts';
var api = require('../../../utils/api.js')
var $ = require('../../../utils/util.js')
var regeneratorRuntime = require('../../../utils/runtime.js')
var app = getApp()
var Store = app.Store

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasMore: true,// 判断 数据是否全部加载完
    isLodingLock: true, //锁 防止数据加载
    pageNum: 1, //页码
    pageList:[], //分页数据列表
    statusBarHeight:0, // 状态栏高度
    title:"工程管理",
    deptId:0,
    projectName:"",//搜索条件
    currentTab: 0, // 当前选中的tab
    nav: [//tab
      { name: '概况', type: 0, num: 0, color: '#dd524d', icon: 'icon-chupiao' },
      { name: '未开工', type: 1, num: 0, color: '#f5a623', icon: 'icon-completed' },
      { name: '已开工', type: 2, num: 0, color: '#16304f', icon: 'icon-gengduo' },
      { name: '已完工', type: 3, num: 0, color: '#16304f', icon: 'icon-tick' },
    ], // tab 
    isShow_ecahrts:true,//显示echarts图 判断位
    _longitude: 116.3972282409668, //当前地图位置的中心点(默认定位北京)
    _latitude: 39.90960456049752, //当前地图位置的中心点(默认定位北京)
    _scale: 13, //当前地图的缩放系数
    markers:[//地图图标

    ],
    problemList:[

    ],//待解决问题列表
    isAdd:false,//新增弹窗确认
    showProblem:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {  
    Store.dispatch({
      type: 'SET_FROM',
      form: {

      },
    })
    let { statusBarHeight } = app.data; // 手机状态栏高度 
    this.setData({
      statusBarHeight, 
    })  
    app._clearFromCache();
      // 初始化需要的数据s 
      var zf_list = await app._selectEnterprise() 
      this.setData({
        deptId: zf_list.data[0].dept_id, 
        title: zf_list.data[0].dept_name, 
        name:  zf_list.data[0].dept_name
      })
      if(this.data.currentTab==0){//整体概览
        this.getOverView();
        wx.stopPullDownRefresh()
      }else{
        await this.getPagServer(1,true);
      }
      this._counts();

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow () {
    var form = Store.getState().formInfor.form
    app._clearFromCache();
    if (!form.selected){
      if(this.data.currentTab!=0){
        await this.getPagServer(1,true);
      }
      this._counts();
      return
    } 
    var key = form.key
    switch (key) {
      case 'selectEnterprise': // 企业和站房列表接口 
        var title=form.selected.dept_name;
        this.setData({
          title: title,
          deptId:form.selected.dept_id, // 站房id
          name:title,
          projectName:""
        })
        if(this.data.currentTab==0){//整体概览
          this.getOverView();
          wx.stopPullDownRefresh()
        }else{
          await this.getPagServer(1,true);
        }
        this._counts();
        break
      }
  },
  onReachBottom() { //滑动到底部触发
    this.loadingMore()
  },
  onPullDownRefresh: function () { // 下拉刷新
    if(this.data.currentTab==0){//整体概览
      this.getOverView();
      wx.stopPullDownRefresh()
    }else{
      this.getPagServer(1, true) //获取分页数据
    }
  },
  loadingMore: function () {  // 加载更多
    if (this.data.isLodingLock) {
      this.setData({
        isLodingLock: false
      })
      if(this.data.currentTab==0){//整体概览
        this.getOverView();
        wx.stopPullDownRefresh()
      }else{
        this.getPagServer()
      }
    }
  },
  tabHanlde(e) { // tab切换
    this.setData({
      currentTab: e.detail.index
    })  
    if(this.data.currentTab==0){
      this.getOverView();
    }else{
      this.getPagServer(1, true) //获取分页数据
    }
    this._counts();
  },
  toAllHandle(e){ //标题栏选择
    var { key } = e.detail 
    switch (key*1){
      case 1: // 选择站房
        this.setData({
          eqIndex: 1, // ---该需求了---
          isShowPop: false
        })
        var { type } = $.detail(e)
        Store.dispatch({
          type: 'SET_FROM',
          form: {
            key: 'selectEnterprise', // 后台要的更改字段 
            type: 1, // 表单类型 1： radio  2：select
            config: {
              
            },
          },
        })
        $.linkurl(`/pages/main/chooseForm/chooseForm`)
        break;
    } 
  },
    //##input 输入##
    input_handle(e) {
      this.setData({
        [e.currentTarget.dataset.key]: e.detail.value
      })
    },
    //##input 输入##
    keywordConfirmHandle(){ // 搜索输入框 
      if(this.data.currentTab==0){//整体概览
        
      }else{
        this.getPagServer(1, true) //获取分页数据
      }
    },
    toAddProject(){
      this.setData({
        isAdd:true
      })
    },
    toAddProjectPage(){
      $.linkurl(`/pages/projectManage/projectManageAdd/projectManageAdd`)
    },
    toProjectPageInfo(e){
      var { item } = $.detail(e)
      $.linkurl(`/pages/projectManage/projectManageInfo/projectManageInfo?id=${item.id}`)
    },
    _counts(){
      api.$get(api.projectManage.counts, {"deptId":this.data.deptId}).then((res) => {
        this.setData({
          nav: [//tab
            { name: '概况', type: 0, num: res.data.total, color: '#dd524d', icon: 'icon-chupiao' },
            { name: '未开工', type: 1, num:res.data.status0, color: '#f5a623', icon: 'icon-completed' },
            { name: '已开工', type: 2, num:res.data.status1, color: '#16304f', icon: 'icon-gengduo' },
            { name: '已完工', type: 3, num: res.data.status2, color: '#16304f', icon: 'icon-tick' },
          ], // tab 
        })
      })
    },
    getOverView(){
      api.$get(api.projectManage.getOverView,{"deptId":this.data.deptId}).then((res)=>{

          var maps=res.data.maps;
          var mapList=[];
          for(var i=0;i<maps.length;i++){
            var map={
              id: maps[i].id
              ,iconPath: "/assets/map_localtion_red.png"
              ,longitude: maps[i].longitude
              ,latitude: maps[i].latitude
              ,width: 30
              ,height: 30
              ,title:maps[i].name
            }
            mapList.push(map);
          }
          this.setData({
            problemList:res.data.problems,
            showProblem:res.data.problems.length!=0? true :false,
            markers:mapList,
            _latitude: mapList.length>0? mapList[0].latitude : 39.90960456049752,
            _longitude:mapList.length>0? mapList[0].longitude :  116.3972282409668
          })
          this.init1(res.data.echarts);
      });
    },
    getPagServer(pageNum, isClickTab = false) { //分页  
      var params = {
        pageNum: pageNum == 1 ? 1 : this.data.pageNum,
        pageSize: 10,
        deptId:this.data.deptId,
        projectName: this.data.projectName,
        projectState: this.data.currentTab==1?0:this.data.currentTab==2?1:this.data.currentTab==3?2:-1,
      } 
      $.getPageList(api, this, api.projectManage.list, params, isClickTab).then((res) => {
        wx.stopPullDownRefresh() // 接口数据请求完停止刷新
      })
    },
    init1( data) {
      this.selectComponent('#mychart1').init((canvas, width, height,dpr) => {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr ,
          
        });
        var option = {
          title: {
            text: '',
            subtext: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data:[ "未开工","已开工","已完工"]
          },
          color: ['#ff7070','#fac858','#91cc75'],
          series: [
            {
              name: '工程数量',
              type: 'pie',
              radius: ['50%', '70%'],
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              data: data,
              emphasis: {
                label: {
                  show: true,
                  fontSize: '25',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
            }
          ]
        };
        chart.setOption(option);
        let index=2;//默认展示第三个
        chart.dispatchAction({
          type: "highlight",
          seriesIndex: 0, 
          dataIndex: index
        });
        chart.dispatchAction({
          type: "showTip",
          seriesIndex: 0, 
          dataIndex: index
        });
        chart.on("click",function(e){
          if(e.dataIndex!=index){
            chart.dispatchAction({
              type: "downplay",
              seriesIndex: 0, 
              dataIndex: index
            });
          } 
        })
        return chart;
      });
    },
    changeProblem(){
      this.setData({
        showProblem:!this.data.showProblem
      })
    }
    
})